<?php
/**
 * User: 269995848@qq.com
 * Date: 2019/3/19 11:46
 * 下注，解析下注规则，生成订单
 */

namespace app\qqbot\service\command;


use app\common\opencode\xyft\Lottery;
use app\lib\enum\Code;
use app\lib\enum\QqBot;
use app\qqbot\model\GameRecord;
use app\qqbot\model\User;
use app\qqbot\service\event\SendMessageEvent;
use app\qqbot\service\myservice\SendMessage;
use app\qqbot\service\src\CQCode;
use think\Db;
use think\Log;

class Rule{

    public function index(array $event){

        $order=$this->accounts($event);

        if($order){
            $qq=floatval($event['sender']['user_id']);
            $from_group=$event['group_id'];
            $name=$event['sender']['nickname'];
            $user_id=\app\qqbot\model\User::RegisterCache($qq,$from_group,false);
            if(!$user_id){
                return SendMessageEvent::sendBack(CQCode::At($qq)."xz失败",$event);
            }

            $user=User::get($user_id);
            if($user->money < $order['totalMoney']){
                return SendMessageEvent::sendBack(CQCode::At($qq)."积分不足",$event);
            }


            $cacheOrder=[
                'qq'=>$qq,
                'from_group'=>$event['group_id'],
                'validBetAmount'=>$order['totalMoney'],
                'billNo'=>makeOrderNo(),
                'name'=>$name,
                'member_id'=>$user_id,
                'betTime'=>$event['time'],
                'gameType'=>'幸运飞艇',
                'betAmount'=>$order['totalMoney'],
                'flag'=>2,
                'reAmount'=>serialize($order),
                'count'=>$order['count'],
                'xzhm'=>$event['message'],
                'odds'=>1.98,
                //一下字段要结算后才有
                'netAmount'=>0,
                'platAmount'=>0,
            ];
            Db::startTrans();
            try{
                redisObj()->rPush(Code::GAME_RECORD,serialize($cacheOrder));
                Db::name('user')->where('id',$user_id)->dec('money',$order['totalMoney'])->update();
                Db::commit();
            }catch(\Exception $e){

                Db::rollback();
                \think\facade\Log::write('下注错误:'.$e->getMessage(),'error');
                return false;
            }
        }else{

            return false;
        }

        SendMessage::betsAfterApplyFromGroup($qq,$from_group,$order['totalMoney'],$order['returnMsg']);exit;
        //return $order['returnMsg'];
    }


    //规则判断
    private function choiceRule($event){
        $rule=QqBot::betsRule();
        $ruleArr=[
            'load'=>'',
            'rule'=>'',
            'money'=>'',
        ];

        $str=trim($event['message']);
        if(preg_match("/[\x7f-\xff]{4,100}/", $str,$match)){

            return false;
        }

        //第一种情况
        if(substr_count($str,"/") == 2){

            $firstLen=strpos($str,'/');
            $lastLen=strripos($str,"/");
            $rule1=substr($str,0,$firstLen);


            if(!is_numeric($rule1) | $rule1 < 0){


                return false;
            }


            $ruleArr['load']=$rule1;

            $rule3=substr($str,$lastLen+1);

            if(!isInt($rule3)){

                return false;
            }
            $ruleArr['money']=(int)$rule3;
            $len=$lastLen-$firstLen;
            $rule2=substr($str,$firstLen+1,$len-1);

            if(preg_match("/^[\x7f-\xff]{1,3}$/", trim($rule2),$match)){

                if(!in_array($match[0],$rule)){

                    return false;
                }
                $ruleArr['rule']=$rule2;
            }elseif($rule2=='0'){
                if(!(preg_match('/\D+/',$rule2)  && (is_numeric($rule2) &&  $rule2 >= 0))){

                    $ruleArr['rule']=$rule2;
                }else{

                    return false;
                }
            }elseif((int)$rule2){
                $ruleArr['rule']=$rule2;
            }else{

                return false;
            }

            return $ruleArr;
        }
        //第二种情况
        if(substr_count($str,"/") == 1){
            $ruleArr['load']='0';
            $rule2=substr($str,0,strpos($str,'/'));

            if(!is_numeric($rule2) | $rule2 <0 ){
                if(preg_match("/^[\x7f-\xff]{1,3}$/", trim($rule2),$match)){
                    if(!in_array($match[0],$rule)){
                        return false;
                    }
                }

            }
            $ruleArr['rule']=$rule2;

            $rule3=substr($str,strpos($str,'/')+1);

            if(!is_numeric($rule3) | $rule3 <= 0){
                return false;
            }
            $ruleArr['money']=$rule3;

            return $ruleArr;
        }

        //第三种情况
        if(preg_match("/^[\x7f-\xff]{1,3}/", $str,$match)){

            if(!in_array($match[0],$rule)){

                return false;
            }

            $rule3=substr($str,3);
            if(!is_numeric($rule3) | $rule3 <= 0){

                return false;
            }
            $ruleArr['load']='1';
            $ruleArr['rule']=$match[0];
            $ruleArr['money']=$rule3;

            return $ruleArr;
        }

        //第四种情况
        if(preg_match("/^(\d+)([\x7f-\xff]{1,3})(\d+)/",$str,$match)){
            file_put_contents('./success.txt',1,8);
            if(!is_numeric($match[1]) | !is_numeric($match[3]) | ($match[3] < 0))return false;
            $ruleArr['load']=$match[1];

            if(!in_array($match[2],$rule)) return false;
            $ruleArr['rule']=$match[2];

            if(!is_numeric($match[3]) | $match[3]<=0) return false;
            $ruleArr['money']=$match[3];

            return $ruleArr;
        }
        return false;
    }


    //生成订单

    /**
     * @param $event
     * @return array|bool
     * user:269995848@qq.com  2019/4/2 20:43
     * 返回订单结构
     *  $jiesuan=[
        'money'=>'',   //总价 总价=每条车道的总数*车道数*下注号码个数*单价
        'singleMoney'=>$arr['money'], //单价
        'rule'=>[],     //下注号详情
        'load'=>[],  //车道详情
        'count'=>0,  //下注次数
        'returnMsg'=>[],
        ];
     */
    private function accounts($event){


        $arr=$this->choiceRule($event);

        if(!$arr){
            return false;
        }

        $jiesuan=[
            'totalMoney'=>0,
            'singleMoney'=>$arr['money'],
            'rule'=>[],
            'load'=>[],
            'count'=>0,
            'returnMsg'=>[],
        ];
        $rule=QqBot::betsRule();
        if(!in_array($arr['rule'],$rule)){
            $jiesuan['totalMoney']=strlen($arr['load'])*strlen($arr['rule'])*$arr['money'];

        }else{  //如果下注的大小单双
            $jiesuan['totalMoney']=strlen($arr['load'])*$arr['money'];

        }

        //处理车道的返回消息
        $num=['1','2','3','4','5','6','7','8','9','0'];
        $loadMsg=[];
        $ruleMsg=[];
        $loadCount=0;
        $ruleCount=0;
        foreach($num as $k=>$v){
            $strLoad="*".substr_count($arr['load'],$v);
            if(substr_count($arr['load'],$v) > 1){
                for($i=0;$i<strlen($arr['load']);$i++){
                    if($arr['load'][$i] == $v){
                        if($v==0) $v='10';
                        array_push($loadMsg,$v.'道'.$strLoad);
                    }
                }

            }else{
                for($i=0;$i<strlen($arr['load']);$i++){

                    if($arr['load'][$i] == $v){
                        if($v==0) $v='10';
                        array_push($loadMsg,$v.'道');
                    }
                }
            }
        }


        //处理投注的返回消息,车道肯定是数字类型，但投注 不一定是数字类型
        if(preg_match("/^[\x7f-\xff]{1,3}$/", $arr['rule'],$match)){

            array_push($ruleMsg,$match[0].'/'.$arr['money']);
            array_push($jiesuan['rule'],$arr['rule']);
        }else{
            foreach($num as $k=>$v){
                $strRule=substr_count($arr['rule'],$v);
                if($strRule > 1){
                    for($i=0;$i<strlen($arr['rule']);$i++){
                        if($arr['rule'][$i] == $v){
                            if($v==0) $v='10';
                            if(!in_array($v."*".$strRule.'/'.$arr['money'] , $ruleMsg))
                                array_push($ruleMsg,$v."*".$strRule.'/'.$arr['money']);

                        }
                    }

                }else{
                    for($i=0;$i<strlen($arr['rule']);$i++){
                        if($arr['rule'][$i] == $v){
                            if($v==0) $v='10';
                            array_push($ruleMsg,$v.'/'.$arr['money']);
                        }
                    }
                }
            }

            //存放下注号
            for($i=0;$i<strlen($arr['rule']);$i++){
                $ruleCount++;
                array_push($jiesuan['rule'],$arr['rule'][$i]==0?'10':$arr['rule'][$i]);
            }
        }

        foreach($loadMsg as $k=>$v){
            foreach($ruleMsg as $v1){
                $v=$v.' '.$v1;
            }
            if(!in_array($v,$jiesuan['returnMsg']))
                array_push($jiesuan['returnMsg'],$v);
        }

        //存放车道
        for($i=0;$i<strlen($arr['load']);$i++){
            $loadCount++;
            array_push($jiesuan['load'],$arr['load'][$i]==0?'10':$arr['load'][$i]);
        }

        $jiesuan['count']=$loadCount*$ruleCount;

        return $jiesuan;
    }


}